import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import '../models/habit.dart';
import '../services/habit_provider.dart';
import '../utils/app_theme.dart';
import 'reminder_screen.dart';

class AddHabitScreen extends StatefulWidget {
  const AddHabitScreen({super.key});

  @override
  State<AddHabitScreen> createState() => _AddHabitScreenState();
}

class _AddHabitScreenState extends State<AddHabitScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _amountController = TextEditingController();
  
  String _frequency = '每天';
  String _icon = 'list';
  Color _color = Color(AppTheme.primaryColor.value);
  List<String> _reminderTimes = [];
  
  final List<String> _frequencyOptions = ['每天', '每周', '每月', '自定义'];
  final List<Map<String, dynamic>> _iconOptions = [
    {'name': '列表', 'value': 'list', 'icon': Icons.list},
    {'name': '水滴', 'value': 'water', 'icon': Icons.water_drop},
    {'name': '运动', 'value': 'exercise', 'icon': Icons.fitness_center},
    {'name': '书本', 'value': 'book', 'icon': Icons.book},
    {'name': '冥想', 'value': 'meditation', 'icon': Icons.self_improvement},
    {'name': '笔记', 'value': 'notes', 'icon': Icons.note},
    {'name': '睡觉', 'value': 'sleep', 'icon': Icons.nightlight},
    {'name': '学习', 'value': 'study', 'icon': Icons.school},
  ];
  
  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    _amountController.dispose();
    super.dispose();
  }
  
  void _showColorPicker() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('选择习惯颜色'),
        content: SingleChildScrollView(
          child: BlockPicker(
            pickerColor: _color,
            onColorChanged: (color) {
              setState(() {
                _color = color;
              });
              Navigator.of(context).pop();
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }
  
  void _showIconPicker() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('选择习惯图标'),
        content: SizedBox(
          width: double.maxFinite,
          child: GridView.builder(
            shrinkWrap: true,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              mainAxisSpacing: 8,
              crossAxisSpacing: 8,
            ),
            itemCount: _iconOptions.length,
            itemBuilder: (context, index) {
              final iconData = _iconOptions[index];
              return InkWell(
                onTap: () {
                  setState(() {
                    _icon = iconData['value'];
                  });
                  Navigator.of(context).pop();
                },
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: _icon == iconData['value'] 
                        ? AppTheme.primaryColor 
                        : AppTheme.borderColor,
                      width: 2,
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        iconData['icon'],
                        color: _icon == iconData['value'] 
                          ? AppTheme.primaryColor 
                          : AppTheme.textPrimaryColor,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        iconData['name'],
                        style: TextStyle(
                          fontSize: 12,
                          color: _icon == iconData['value'] 
                            ? AppTheme.primaryColor 
                            : AppTheme.textPrimaryColor,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }
  
  void _addReminder() async {
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => ReminderScreen(
          initialReminders: _reminderTimes,
        ),
      ),
    );
    
    if (result != null && result is List<String>) {
      setState(() {
        _reminderTimes = result;
      });
    }
  }
  
  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      final newHabit = Habit(
        name: _nameController.text,
        description: _descriptionController.text,
        icon: _icon,
        colorValue: _color.value,
        frequency: _frequency,
        amount: _amountController.text,
        reminderTimes: _reminderTimes,
      );
      
      Provider.of<HabitProvider>(context, listen: false).addHabit(newHabit);
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加新习惯'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Name input
              TextFormField(
                controller: _nameController,
                decoration: AppTheme.inputDecoration(
                  '习惯名称',
                  hintText: '例如：冥想、阅读、运动...',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入习惯名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              
              // Description input
              TextFormField(
                controller: _descriptionController,
                decoration: AppTheme.inputDecoration(
                  '描述（可选）',
                  hintText: '为什么要培养这个习惯？',
                ),
                maxLines: 3,
              ),
              const SizedBox(height: 16),
              
              // Amount input
              TextFormField(
                controller: _amountController,
                decoration: AppTheme.inputDecoration(
                  '数量/时长',
                  hintText: '例如：10分钟、8杯水等',
                ),
              ),
              const SizedBox(height: 16),
              
              // Frequency selection
              const Text('执行频率', style: AppTheme.bodyStyle),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                children: _frequencyOptions.map((freq) {
                  return ChoiceChip(
                    label: Text(freq),
                    selected: _frequency == freq,
                    onSelected: (selected) {
                      if (selected) {
                        setState(() {
                          _frequency = freq;
                        });
                      }
                    },
                  );
                }).toList(),
              ),
              const SizedBox(height: 16),
              
              // Color and Icon selection
              Row(
                children: [
                  Expanded(
                    child: InkWell(
                      onTap: _showColorPicker,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          border: Border.all(color: AppTheme.borderColor),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 24,
                              height: 24,
                              decoration: BoxDecoration(
                                color: _color,
                                shape: BoxShape.circle,
                              ),
                            ),
                            const SizedBox(width: 8),
                            const Text('选择颜色'),
                          ],
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: InkWell(
                      onTap: _showIconPicker,
                      child: Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          border: Border.all(color: AppTheme.borderColor),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              _iconOptions
                                  .firstWhere((i) => i['value'] == _icon)['icon'],
                            ),
                            const SizedBox(width: 8),
                            const Text('选择图标'),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              
              // Reminder times
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  border: Border.all(color: AppTheme.borderColor),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('提醒时间', style: AppTheme.bodyStyle),
                    const SizedBox(height: 8),
                    if (_reminderTimes.isEmpty)
                      const Text(
                        '未设置提醒',
                        style: TextStyle(color: AppTheme.textSecondaryColor),
                      )
                    else
                      Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: _reminderTimes.map((time) {
                          return Chip(
                            label: Text(time),
                            deleteIcon: const Icon(Icons.close, size: 16),
                            onDeleted: () {
                              setState(() {
                                _reminderTimes.remove(time);
                              });
                            },
                          );
                        }).toList(),
                      ),
                    const SizedBox(height: 8),
                    OutlinedButton.icon(
                      onPressed: _addReminder,
                      icon: const Icon(Icons.alarm_add),
                      label: const Text('设置提醒'),
                      style: AppTheme.outlineButtonStyle,
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 24),
              
              // Submit button
              ElevatedButton(
                onPressed: _submitForm,
                style: AppTheme.primaryButtonStyle,
                child: const Text('保存习惯'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
